package com.woniu.controller;

import cn.hutool.core.date.DateTime;
import com.woniu.entity.*;
import com.woniu.entity.dto.CtfScoreDetailDTO;
import com.woniu.service.*;
import com.woniu.util.ResponseData;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.relational.core.sql.In;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * @ClassName CtfScoreController
 * @Description 得分表API
 * @Author puhaohui
 * @Date 2025/6/10 10:35
 * @Version 1.0
 */

@RestController
@RequestMapping("/ctf-score")
public class CtfScoreController {

    @Autowired
    private CtfScoreService ctfScoreService;

    @Autowired
    private CtfContestService ctfContestService;

    @Autowired
    private CtfRangeService  ctfRangeService;
    @Autowired
    private CtfScoreDifficultyService  ctfScoreDifficultyService;
    /**
     * @Description 新增得分记录
     */
    @PostMapping
    public ResponseData<String> add(@RequestBody CtfScore score) {
        List<CtfContainer> containers = ctfContestService.getContainersByContestId(score.getContestId());
        if (containers == null || containers.isEmpty()) {
            return ResponseData.fail(201,"容器不存在");
        }
        Integer contestId = score.getContestId(); // 假设 CtfScore 已添加 contestId 字段
        if (contestId == null) {
            return ResponseData.fail(201,"考试不存在");
        }
        // 获取容器信息
        CtfContest container  = ctfContestService.getById(contestId);
        if (container == null) {
            return ResponseData.fail(201,"容器不存在");
        }
        Date createTime = container.getCreateTime();
        Date updateTime = container.getUpdateTime();
        if (createTime == null || updateTime == null) {
            return ResponseData.fail(300,"容器时间信息不完整");
        }
        Double total = 0.0;

        //遍历containers
        for (CtfContainer container1: containers) {
            // 计算时间差（单位：分钟）
            long diffInMillies = container1.getUpdateTime().getTime() - container1.getCreateTime().getTime();
            long diffInMinutes = diffInMillies / (60 * 1000);
            String rangeId = container1.getRangeId();
            Integer difficultyId = ctfRangeService.selectDifficultyIdByRangeId(rangeId);
            CtfScoreDifficulty  scoreDifficulty = ctfScoreDifficultyService.getById(difficultyId);
            Double scoreValue = scoreDifficulty.getScoreValue();
            //得分算法
            double totalScore = 0.0;
            if (diffInMinutes>=30){
                totalScore  = scoreValue;

            }else if (diffInMinutes<=0){
                totalScore  = 0.0;
            }
            else{
                totalScore = scoreValue* (diffInMinutes / 30.0);
                totalScore = new BigDecimal(totalScore).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
//                score.setTotalScore(totalScore);
            }
            total=totalScore+total;
        }
        //从containers中拿到rangeId
//        Integer rangeId = containers.get(0).getRangeId();
        score.setTotalScore(total);
        score.setCreateTime(DateTime.now());
        ctfScoreService.save(score);
        return ResponseData.ok("新增成功");
    }

    /**
     * 删除得分记录
     */
    @DeleteMapping("/{id}")
    public ResponseData<String> delete(@PathVariable Integer id) {
        ctfScoreService.removeById(id);
        return ResponseData.ok("删除成功");
    }

    /**
     * 修改得分记录
     */
    @PutMapping
    public ResponseData<String> update(@RequestBody CtfScore score) {
        score.setUpdateTime(DateTime.now());
        ctfScoreService.updateById(score);
        return ResponseData.ok("更新成功");
    }


    /**
     * 查询所有得分记录
     */
    @GetMapping
    public ResponseData<List<CtfScore>> list() {
        List<CtfScore> list = ctfScoreService.list();
        return ResponseData.ok(list);
    }

//    @GetMapping("/listByContest/{contestId}")
//    public ResponseData<List<CtfScoreDetailDTO>> listByContest(@PathVariable("contestId") Integer contestId){
//        System.out.println("imhere");
//        List<CtfScoreDetailDTO> list = ctfScoreService.listByContestWithUserInfoAndContestInfo(contestId);
//        return ResponseData.ok(list);
//    }
  /*根据考试ID查询得分记录
  需要传入contestId
   */
    @PostMapping("/listByContest")
    public ResponseData<List<CtfScoreDetailDTO>> listByContest(@RequestBody CtfScore score ){
        List<CtfScoreDetailDTO> list = ctfScoreService.listByContestWithUserInfoAndContestInfo(score.getContestId());
        return ResponseData.ok(list);
    }
    /**
     * 根据ID查询得分记录
     */
    @GetMapping("/{id}")
    public ResponseData<CtfScore> getById(@PathVariable Integer id) {
//        List<CtfContainer> score = ctfContestService.getContainersByContestId(id);
        CtfScore score = ctfScoreService.getById(id);
        return ResponseData.ok(score);
    }
}